package com.study.design.pattern.pattern.structural.proxy.cglibproxy;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
import java.lang.reflect.Method;

/**
 * @Author: gongsl
 * @Date: 2025-03-19 22:06
 * @description: CGLIB代理类
 */
public class PaymentServiceCGLIBProxy implements MethodInterceptor {
    private Object target;

    public PaymentServiceCGLIBProxy(Object target) {
        this.target = target;
    }

    @Override
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
        // 在支付前做额外操作，例如记录日志
        System.out.println("CGLIB -- Logging: Payment is about to be processed.");
        // 调用目标类的实际方法
        Object result = method.invoke(target, args);
        // 在支付后做额外操作，例如记录日志
        System.out.println("CGLIB -- Logging: Payment has been processed.");
        return result;
    }

    /**
     * 创建代理对象
     */
    public Object getProxy() {
        Enhancer enhancer = new Enhancer();
        // 设置目标类
        enhancer.setSuperclass(target.getClass());
        // 设置回调（拦截器）
        enhancer.setCallback(this);
        // 创建代理对象
        return enhancer.create();
    }
}
